<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="login-header">
          <h2>系统登录</h2>
          <el-radio-group v-model="loginType" size="large">
            <el-radio-button label="account">账号密码登录</el-radio-button>
            <el-radio-button label="phone">手机号登录</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <el-form 
        :model="loginForm" 
        :rules="rules" 
        ref="loginFormRef"
        @keyup.enter="handleLogin"
      >
        <!-- 账号密码登录表单 -->
        <template v-if="loginType === 'account'">
          <el-form-item prop="userName">
            <el-input 
              v-model="loginForm.userName"
              placeholder="请输入用户名"
              :prefix-icon="User"
            />
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input 
              v-model="loginForm.passWord"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>
        </template>

        <!-- 手机号登录表单 -->
        <template v-else>
          <el-form-item prop="phone">
            <el-input 
              v-model="loginForm.phone"
              placeholder="请输入手机号"
              :prefix-icon="Iphone"
            />
          </el-form-item>
          
          <el-form-item prop="smsCode" style="margin-bottom: 20px;">
            <div style="display: flex; gap: 10px;">
              <el-input 
                v-model="loginForm.smsCode"  
                placeholder="请输入验证码"
                :prefix-icon="Lock"
                style="flex: 1;"
              />
              <el-button 
                type="primary" 
                :disabled="!!timer"
                @click="handleSendCode"
                style="width: 120px;"
              >
                {{ timer ? `${countdown}s后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </template>

        <el-form-item class="login-options">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <el-link type="primary" class="forget-pwd">忘记密码？</el-link>
        </el-form-item>

        <el-button 
          type="primary" 
          class="login-btn" 
          :loading="loading"
          @click="handleLogin"
        >
          登录
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onBeforeUnmount } from 'vue'
import { User, Lock, Iphone, Key } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { login } from '@/api/user'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)
const loginType = ref('account') // 登录方式
const timer = ref(null) // 验证码倒计时定时器
const countdown = ref(60) // 倒计时秒数

// 登录表单数据
const loginForm = ref({
  phone: '',
  smsCode: '',      // 验证码输入框的值
  username: '',
  password: '',
  remember: false
})

// 表单验证规则
const rules = reactive({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' }
  ],
  passWord: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码必须为6位数字', trigger: 'blur' }
  ]
})

// 监听登录方式变化，重置表单
watch(loginType, () => {
  loginFormRef.value?.resetFields()
})

// 发送验证码
const handleSendCode = async () => {
  try {
    // 验证手机号
    await loginFormRef.value.validateField('phone')
    
    // 调用发送验证码接口
    const response = await fetch('http://localhost:9004/api/cloud/sys/sendSms', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        phone: loginForm.value.phone
      })
    })

    const data = await response.json()
    console.log('验证码接口响应:', data) // 调试日志
    
    if (data.code === 200) {
      ElMessage.success('验证码发送成功')
      // 开始倒计时
      countdown.value = 60
      timer.value = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer.value)
          timer.value = null
        }
      }, 1000)
    } else {
      ElMessage.error(data.msg || '验证码发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送验证码失败，请检查手机号是否正确')
  }
}

// 登录处理
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    
    console.log('登录表单数据:', loginForm.value)
    
    const loginData = {
      clientType: 0,
      way: loginType.value === 'phone' ? 1 : 0,
      phone: loginForm.value.phone,
      smsCode: Number(loginForm.value.smsCode)
    }

    console.log('发送的登录请求数据:', loginData)

    const response = await fetch('http://localhost:9004/api/cloud/sys/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(loginData)
    })

    const data = await response.json()
    console.log('登录响应:', data)

    if (data.code === 200 && data.success) {
      ElMessage.success('登录成功')
      localStorage.setItem('token', data.result.token)
      router.push('/')
    } else {
      ElMessage.error(data.message || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请检查输入')
  }
}

// 组件销毁时清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>
<style scoped lang="scss">
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-card {
  width: 420px;
  
  :deep(.el-card__header) {
    padding: 0;
  }
}

.login-header {
  padding: 20px;
  text-align: center;
  
  h2 {
    margin: 0 0 20px;
  }
}

.login-options {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}

.forget-pwd {
  margin-left: auto;
}

:deep(.el-input-group__append) {
  padding: 0;
  overflow: hidden;
  margin-left: 10px; /* 添加间距 */
  border: 1px solid var(--el-border-color); /* 添加边框 */
  border-radius: 4px; /* 添加圆角 */
  
  .verify-code-btn {
    margin: 0;
    padding: 0 15px;
    height: 100%;
    border: none;
    border-radius: 4px; /* 与外层容器保持一致的圆角 */
    
    &:hover, &:focus {
      border: none;
      outline: none;
    }
    
    &:disabled {
      border: none;
    }
  }
}

/* 确保输入框和按钮的高度一致 */
:deep(.el-input__wrapper) {
  height: 32px;
  line-height: 32px;
}

:deep(.verify-code-btn) {
  height: 32px;
  line-height: 32px;
  min-height: 32px;
}
</style>
